package com.loadmore.ibook;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.loadmore.common.App;
import com.loadmore.common.adapter.callback.RVBaseClickListener;
import com.loadmore.common.adapter.callback.RVBaseLongClickListener;
import com.loadmore.common.api.Api;
import com.loadmore.common.bean.Book;
import com.loadmore.common.bean.Response;
import com.loadmore.common.constants.BookConstants;
import com.loadmore.common.constants.Constants;
import com.loadmore.common.db.gen.BookDao;
import com.loadmore.common.net.RequestUtil;
import com.loadmore.common.net.impl.RequestCallBack;
import com.loadmore.common.recyclerview.WrapLinearLayoutManager;
import com.loadmore.common.util.JsonUtil;
import com.loadmore.common.widget.ToolbarLayout;
import com.loadmore.ibook.adapter.BookAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainActivity extends AppCompatActivity implements ToolbarLayout.MenuClickListener, View.OnClickListener {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView book_list;
    private TextView book_info;
    public static final int SearchIsbn = 0x0001;
    private int REQUEST_ISBN = 0x0001;
    private String isbn;
    private BookAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        book_list = findViewById(R.id.book_list);
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        book_list.setLayoutManager(new WrapLinearLayoutManager(this));
        adapter = new BookAdapter(this);
        book_list.setAdapter(adapter);
        ToolbarLayout toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setMenuClickListener(this);
        toolbar.hideBackView();
        toolbar.setTitle("IBook");
        book_info = findViewById(R.id.book_info);
        book_info.setOnClickListener(this);
        ImageView searchIcon = toolbar.addRightImage(0x0001);
        searchIcon.setImageResource(R.mipmap.icon_search);
        refreshLayout.setEnableLoadmore(true);
        adapter.setClickListener(new RVBaseClickListener() {
            @Override
            public void onClick(int position) {
                Book book = (Book) adapter.getItem(position);
                Intent intent = new Intent(getApplicationContext(), ISBNActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.DATA, book);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        adapter.setLongClickListener(new RVBaseLongClickListener() {
            @Override
            public void onLongClick(int position) {
                Book book = (Book) adapter.getItem(position);
                Intent intent = new Intent(getApplicationContext(), ISBNActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.DATA, book);
                bundle.putBoolean(BookConstants.EDIT, true);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(final RefreshLayout refreshlayout) {
                queryBook(false);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                queryBook(true);
            }
        });
        queryBook(true);
    }

    @Override
    public void onMenuClick(int id) {
        switch (id) {
            case SearchIsbn:
                MainActivityPermissionsDispatcher.scanISBNWithCheck(this);
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ISBN) {            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    isbn = bundle.getString(CodeUtils.RESULT_STRING);
                    book_info.setText("ISBN: " + isbn);
                    queryBook();

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void queryBook() {
        Map<String, String> params = new HashMap<>();
        params.put("isbn", isbn);
        RequestUtil.getInstance(this).post(Api.query_isbn, params, new RequestCallBack() {
            @Override
            public void onSuccess(String data) {
                Response response = JsonUtil.getJson(data, Response.class);
                if (response != null && response.getCode() == 200) {
                    List<Book> books = JsonUtil.getJsonList(response.getData(), Book.class);
                    if (books == null || books.size() == 0) {
                        queryISBN(false);
                    } else {
                        Book book = books.get(0);
                        int index = adapter.queryBookIndex(book.getIsbn());
                        if (index > 0) {
                            book_list.smoothScrollToPosition(index);
                        }
                        queryISBN(true);
                    }
                }

            }

            @Override
            public void onError(String error) {

            }
        });
    }

    private void queryISBN(final boolean update) {
        RequestUtil.getInstance(this).request(Api.isbn + isbn, new RequestCallBack() {
            @Override
            public void onSuccess(String data) {
                Book book = JsonUtil.getJson(data, Book.class);
                insertBook(book, update);
            }

            @Override
            public void onError(String error) {

            }
        });
    }

    private void insertBook(Book book, final boolean update) {

        if (book == null)
            return;
        Map<String, String> params = new HashMap<>();
        params.put("title", book.getTitle());
        params.put("image", book.getImage());
        params.put("catalog", book.getCatalog());
        if (update) {
            params.put("isbn", book.getIsbn());
            params.put("author", book.getIsbn13());
        } else {

            params.put("isbn", book.getIsbn13());
            if (!TextUtils.equals("null", book.getAuthor()) && !TextUtils.isEmpty(book.getAuthor())) {
                JSONArray jsonArray = JSONArray.parseArray(book.getAuthor());
                if (jsonArray != null) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        stringBuilder.append(jsonArray.getString(i));
                        if (i != jsonArray.size() - 1) {
                            stringBuilder.append(",");
                        }
                    }
                    params.put("author", stringBuilder.toString());
                }
            }
        }
        params.put("price", book.getPrice());
        params.put("subtitle", book.getSubtitle());
        params.put("publisher", book.getPublisher());
        params.put("summary", book.getSummary());
        RequestUtil.getInstance(this).post(Api.insert_isbn, params, new RequestCallBack() {
            @Override
            public void onSuccess(String data) {

                Response response = JsonUtil.getJson(data, Response.class);
                if (response != null && response.getCode() == 200 && !TextUtils.isEmpty(response.getData())) {
                    if (update)
                        return;
                    queryBook(true);
                } else {
                    Toast.makeText(MainActivity.this, "insert failed", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(String error) {

            }
        });
    }


    private void queryBook(final boolean isRefresh) {
        if (isRefresh) {
            refreshLayout.autoRefresh();
        }
        int offset = isRefresh ? 0 : adapter.getItemCount();
        String url = Api.query_isbn + "?offset=" + offset;
//
//        if (adapter.getItemCount() == 0 && isRefresh) {
//            List<Book> books = App.getDao().queryBuilder(Book.class).orderDesc(BookDao.Properties.Create_time).limit(10).offset(offset).list();
//            if (books != null) {
//                adapter.append(books);
//            }
//        }

        RequestUtil.getInstance(this).request(url, new RequestCallBack() {
            @Override
            public void onSuccess(String data) {

                if (isRefresh) {
                    adapter.clear();
                    refreshLayout.finishRefresh();
                } else {
                    refreshLayout.finishLoadmore();
                }
                if (TextUtils.isEmpty(data))
                    return;
                Response response = JsonUtil.getJson(data, Response.class);
                if (response != null && response.getCode() == 200 && !TextUtils.isEmpty(response.getData())) {
                    List<Book> books = JsonUtil.getJsonList(response.getData(), Book.class);
                    if (books != null) {
                        if (isRefresh) {

                            App.getDao().getBookDao().deleteAll();
                        }
                        for (int i = 0; i < books.size(); i++) {
                            App.getDao().insert(books.get(i));
                        }
                        adapter.append(books);

                    }
                }

            }

            @Override
            public void onError(String error) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.book_info:
                if (TextUtils.isEmpty(isbn)) {
                    MainActivityPermissionsDispatcher.scanISBNWithCheck(this);
                    return;
                }
                break;
        }
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    public void scanISBN() {
        Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_ISBN);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("hh")
                .setPositiveButton("hh", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("ll", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void showDeniedForCamera() {
        Toast.makeText(this, "Denied", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void showNeverAskForCamera() {
        Toast.makeText(this, "never", Toast.LENGTH_SHORT).show();
    }

}
